package com.bamboo.mcp.client.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class ClientController {
    private static final Logger logger = LoggerFactory.getLogger(ClientController.class);
    private static final String DEFAULT_PROMPT = "你是一个编程高手，请根据内容筛选出对应的工具，并把相关的参数填充好！,如果有选择对应的工具请访问对应的服务，并返回结果！";

    private ChatClient chatClient;
    /*
      访问 OpenAI 服务模型
     */

    private final OpenAiChatModel openAiChatModel;


    private final ToolCallbackProvider toolCallbackProvider;


    public ClientController(OpenAiChatModel openAiChatModel,
                            ToolCallbackProvider toolCallbackProvider) {
        this.openAiChatModel = openAiChatModel;

        this.toolCallbackProvider = toolCallbackProvider;
        this.chatClient = ChatClient.builder(openAiChatModel)
                // 实现 Logger 的 Advisor
                .defaultAdvisors(new SimpleLoggerAdvisor())
                // 默认参数
                .defaultOptions(ChatOptions.builder().topP(0.7).build()).build();
    }

    @GetMapping(value = "/chat", produces = {MediaType.TEXT_EVENT_STREAM_VALUE, MediaType.APPLICATION_JSON_VALUE})
    public Mono<String> chat(@RequestParam(value = "message", defaultValue = "查询当前时间") String message) {
        logger.info("chat,RequestParam:{}", message);
        return Mono.fromCallable(() -> {
            try {
                ToolCallback[] toolCallbacks = toolCallbackProvider.getToolCallbacks();
                ChatClient.CallResponseSpec callResponseSpec = chatClient.prompt(message)
                        .toolCallbacks(toolCallbacks)
                        .system(DEFAULT_PROMPT)
                        .call();
                String content = callResponseSpec.content();
                logger.info("chat,Response:{}", content);
                return content;
            } catch (Exception e) {
                logger.error("Chat request failed", e);
                return "请求失败: " + e.getMessage();
            }
        });
    }
}